// DOM 元素
const menuItems = document.querySelectorAll(".menu li");
const demosGrid = document.getElementById("demosGrid");

// 当前选中的分类
let currentCategory = "all";

// 分页配置
const PAGINATION_CONFIG = {
  pageSize: 40,
  currentPage: 1,
};

// 当前显示的示例数据
let currentDemos = [];

// 主题切换逻辑
const themeToggle = document.getElementById("themeToggle");
const themeIcon = document.getElementById("themeIcon");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

// 从本地存储中获取主题设置
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
  document.documentElement.setAttribute("data-theme", savedTheme);
  updateThemeIcon(savedTheme);
} else if (prefersDarkScheme.matches) {
  // 如果用户系统偏好暗色主题，自动切换到暗色模式
  document.documentElement.setAttribute("data-theme", "dark");
  updateThemeIcon("dark");
}

// 监听系统主题变化
prefersDarkScheme.addEventListener("change", (e) => {
  const newTheme = e.matches ? "dark" : "light";
  document.documentElement.setAttribute("data-theme", newTheme);
  updateThemeIcon(newTheme);
  localStorage.setItem("theme", newTheme);
});

// 切换主题
if (themeToggle) {
  themeToggle.addEventListener("click", () => {
    const currentTheme =
      document.documentElement.getAttribute("data-theme") || "light";
    const newTheme = currentTheme === "light" ? "dark" : "light";

    document.documentElement.setAttribute("data-theme", newTheme);
    localStorage.setItem("theme", newTheme);
    updateThemeIcon(newTheme);
  });
}

// 更新主题图标
function updateThemeIcon(theme) {
  if (themeIcon) {
    themeIcon.className = theme === "dark" ? "ri-moon-line" : "ri-sun-line";
  }
}

// 初始化页面
function initializePage() {
  // 初始化菜单
  initializeMenu();

  // 绑定菜单点击事件
  bindMenuEvents();

  // 初始加载所有示例
  filterDemos("all");
}

// 初始化菜单
function initializeMenu() {
  const menuList = document.querySelector(".menu");
  const categories = demosData.getCategories();

  menuList.innerHTML = categories
    .map(
      (category) => `
        <li data-category="${category.id}" class="${
        category.id === "all" ? "active" : ""
      }">${category.name}</li>
    `
    )
    .join("");
}

// 绑定菜单事件
function bindMenuEvents() {
  const menuItems = document.querySelectorAll(".menu li");
  menuItems.forEach((item) => {
    item.addEventListener("click", () => {
      const category = item.dataset.category;
      setActiveCategory(category);
      filterDemos(category);
    });
  });
}

// 设置活动分类
function setActiveCategory(category) {
  const menuItems = document.querySelectorAll(".menu li");
  menuItems.forEach((item) => {
    item.classList.remove("active");
    if (item.dataset.category === category) {
      item.classList.add("active");
    }
  });
  currentCategory = category;
}

// 过滤并显示示例
function filterDemos(category) {
  const filteredDemos = demosData.getDemosByCategory(category);
  currentDemos = filteredDemos;
  PAGINATION_CONFIG.currentPage = 1; // 重置到第一页
  renderDemosWithPagination(filteredDemos);
}

// 分页渲染示例
function renderDemosWithPagination(demosToRender) {
  const startIndex =
    (PAGINATION_CONFIG.currentPage - 1) * PAGINATION_CONFIG.pageSize;
  const endIndex = startIndex + PAGINATION_CONFIG.pageSize;
  const currentPageDemos = demosToRender.slice(startIndex, endIndex);

  renderDemos(currentPageDemos);
  renderPagination(demosToRender.length);
}

// 渲染示例列表（带懒加载）
function renderDemos(demosToRender) {
  demosGrid.innerHTML = demosToRender
    .map(
      (demo) => `
        <div class="demo-item" onclick="openDemo('${demo.path}')">
            <div class="demo-info">
                <img data-src="${demo.preview}" 
                     alt="${demo.name}"
                     class="lazy-image"
                     loading="lazy">
                <h3>${demo.name}</h3>
            </div>
        </div>
    `
    )
    .join("");

  // 初始化懒加载
  initLazyLoading();
}

// 懒加载实现
function initLazyLoading() {
  const lazyImages = document.querySelectorAll(".lazy-image");

  if ("IntersectionObserver" in window) {
    const imageObserver = new IntersectionObserver(
      (entries, observer) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src;
            img.classList.remove("lazy-image");
            img.classList.add("loaded");
            observer.unobserve(img);
          }
        });
      },
      {
        rootMargin: "50px 0px", // 提前50px开始加载
      }
    );

    lazyImages.forEach((img) => imageObserver.observe(img));
  } else {
    // 降级处理：直接加载所有图片
    lazyImages.forEach((img) => {
      img.src = img.dataset.src;
      img.classList.remove("lazy-image");
      img.classList.add("loaded");
    });
  }
}

// 渲染分页控件
function renderPagination(totalCount) {
  const totalPages = Math.ceil(totalCount / PAGINATION_CONFIG.pageSize);

  if (totalPages <= 1) {
    // 如果只有一页，移除分页控件
    const existingPagination = document.querySelector(".pagination-container");
    if (existingPagination) {
      existingPagination.remove();
    }
    return;
  }

  const paginationHTML = `
    <div class="pagination">
      <button onclick="changePage(${PAGINATION_CONFIG.currentPage - 1})" 
              class="pagination-btn prev-btn"
              ${PAGINATION_CONFIG.currentPage === 1 ? "disabled" : ""}>
        <i class="ri-arrow-left-line"></i>
        上一页
      </button>
      <div class="page-info">
        <span class="current-page">${PAGINATION_CONFIG.currentPage}</span>
        <span class="separator">/</span>
        <span class="total-pages">${totalPages}</span>
      </div>
      <button onclick="changePage(${PAGINATION_CONFIG.currentPage + 1})"
              class="pagination-btn next-btn"
              ${PAGINATION_CONFIG.currentPage === totalPages ? "disabled" : ""}>
        下一页
        <i class="ri-arrow-right-line"></i>
      </button>
    </div>
  `;

  // 在demosGrid后添加分页控件
  let paginationContainer = document.querySelector(".pagination-container");
  if (!paginationContainer) {
    paginationContainer = document.createElement("div");
    paginationContainer.className = "pagination-container";
    demosGrid.parentNode.appendChild(paginationContainer);
  }
  paginationContainer.innerHTML = paginationHTML;
}

// 切换页面
function changePage(newPage) {
  const totalPages = Math.ceil(
    currentDemos.length / PAGINATION_CONFIG.pageSize
  );

  if (newPage < 1 || newPage > totalPages) {
    return;
  }

  PAGINATION_CONFIG.currentPage = newPage;
  renderDemosWithPagination(currentDemos);

  // 滚动到顶部
  demosGrid.scrollIntoView({ behavior: "smooth" });
}

// 打开示例页面
function openDemo(path) {
  window.open(path, "_blank");
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", initializePage);
